package com.suishoupai.xmb.service;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suishoupai.xmb.Security.MyUserDetail;
import com.suishoupai.xmb.dao.*;
import com.suishoupai.xmb.entity.*;
import com.suishoupai.xmb.exception.XmbException;
import com.suishoupai.xmb.utils.PasswordUtil;
import com.suishoupai.xmb.utils.SecurityUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * Created by caojian on 2017/4/11.
 */
@Service
public class UserWxService {

    private static final Log LOG = LogFactory.getLog(UserWxService.class);

    @Value("${wx.appid}")
    private String WX_APPID;
    @Value("${wx.session-key}")
    private String WX_SESSION_KEY;

    @Autowired
    private CutUserWxMapper cutUserWxMapper;
    @Autowired
    private UserWxMapper userWxMapper;
    @Autowired
    private CutUserMapper cutUserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserBuyMapper userBuyMapper;
    @Autowired
    private CutUserBuyMapper cutUserBuyMapper;
    @Autowired
    private CutBlacklistMapper cutBlacklistMapper;
    @Autowired
    private SessionRegistry sessionRegistry;
    @Autowired
    private HttpService httpService;

    /**
     * code换openid
     *
     * @param code
     * @return
     */
    public String code2openId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WX_APPID + "&secret=" + WX_SESSION_KEY + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            String result = httpService.get(url);
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.get("errcode") != null) {
                LOG.info("code2openId error:" + result);
            }
            return jsonObject.get("openid").toString();
        } catch (XmbException e) {
            e.printStackTrace();
            throw new RuntimeException("code换openid失败！");
        }
    }

    /**
     * 第一次插入数据库,第二次及以后更新信息
     *
     * @return
     */
    @Transactional
    public void login(UserWx userWx, UserBuy userBuy, String sessionId) throws XmbException {
        String openId = userWx.getOpenId();
        UserWx temp = cutUserWxMapper.selectByPrimaryKey(openId);
        if (temp != null) {
            //检查黑名单
            Blacklist blacklist = cutBlacklistMapper.selectByPrimaryKey(temp.getUserId());
            if (blacklist != null) {
                throw XmbException.newError("账号已被系统冻结！(原因：" + blacklist.getDescription() + ")");
            }
            //更新信息
            userBuy.setUserId(temp.getUserId());
            if (cutUserBuyMapper.updateByPrimaryKeySelective(userBuy) == 0) {
                throw new RuntimeException("更新用户信息失败");
            }
            User user = cutUserMapper.selectByPrimaryKey(temp.getUserId());
            SecurityUserUtil.setAuth(user);
            sessionRegistry.registerNewSession(sessionId, new MyUserDetail(user));
            return;
        }
        //没有该用户，说明该用户第一次登录
        User user = new User();
        user.setRole(RoleEnum.USER.getValue());
        user.setCreateTime(System.currentTimeMillis());
        String email = UUID.randomUUID().toString() + "@wx.com";
        user.setEmail(email);
        String password = UUID.randomUUID().toString();
        password = PasswordUtil.encoder(email, password);
        user.setPassword(password);
        if (userMapper.insertSelective(user) == 0) {
            throw new RuntimeException("注册失败");
        }
        userWx.setUserId(user.getId());
        userWx.setCreateTime(System.currentTimeMillis());
        if (userWxMapper.insertSelective(userWx) == 0) {
            throw new RuntimeException("注册失败");
        }
        userBuy.setUserId(user.getId());
        userBuy.setCreateTime(System.currentTimeMillis());
        if (userBuyMapper.insertSelective(userBuy) == 0) {
            throw new RuntimeException("注册失败");
        }
        SecurityUserUtil.setAuth(user);
        sessionRegistry.registerNewSession(sessionId, new MyUserDetail(user));

    }
}
